<script setup>
import { ref, reactive, watch } from 'vue'
import { CloseBold } from '@element-plus/icons-vue'
const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  },
  productId: {
    type: Number,
    default: 0
  }
})

const formRef = ref(null)
const form = reactive({
  parameterList: []
})
const emit = defineEmits(['update:modelValue'])

// 旧手机号
const oldPhone = (rule, value, callback, index) => {
  if (!value) {
    return callback(new Error('请输入参数项'))
  } else {
    for (let i = 0; i < index; i++) {
      if (form.parameterList[i].parameterKey === value) {
        return callback(new Error('参数项不能重复'))
      }
    }
    callback()
  }
}

watch(() => props.modelValue, (newVal) => {
  form.parameterList = newVal
}, { immediate: true, deep: true })

const itemAdd = () => {
  form.parameterList.push({
    productId: props.productId,
    parameterKey: '',
    parameterValue: ''
  })
}

const itemDel = (index) => {
  form.parameterList.splice(index, 1)
}

function submitForm () {
  return new Promise((resolve, reject) => {
    formRef.value.validate((valid) => {
      if (valid) {
        emit('update:modelValue', form.parameterList)
        resolve()
      } else {
        reject(new Error('错误'))
      }
    })
  })
}

defineExpose({
  submitForm
})
</script>

<template>
  <el-form
    ref="formRef"
    class="form"
    :model="form"
    label-width="0px"
  >
    <div v-for="(item,index) in form.parameterList" :key="index" class="group">
      <el-form-item
        label=""
        :prop="`parameterList.${index}.parameterKey`"
        :rules="[{
          required: true,
          validator: (rule, value, callback) => oldPhone(rule, value, callback, index),
          trigger: 'blur'
        }]"
      >
        <el-input
          v-model="item.parameterKey"
          class="input"
          placeholder="请输入参数项"
          maxlength="100"
          clearable
        />
      </el-form-item>
      <el-form-item
        label=""
        :prop="`parameterList.${index}.parameterValue`"
        :rules="[{ required: true, message: '参数值不能为空', trigger: 'blur' }]"
      >
        <el-input
          v-model="item.parameterValue"
          class="input"
          placeholder="请输入参数值"
          maxlength="100"
          clearable
        />
      </el-form-item>
      <el-button class="btn-del" type="danger" :icon="CloseBold" circle size="small" @click="itemDel(index)" />
    </div>
    <el-button type="primary" @click="itemAdd">添加参数</el-button>
  </el-form>
</template>

<style scoped lang="scss">
.form{
  flex-wrap: wrap;
  .group{
    display: flex;
    width: 100%;
    margin-bottom: 15px;
    .el-form-item{
      width: 218px;
      margin-right: 5px;
    }
    .btn-del{
      margin-top: 5px;
    }
  }
}
</style>
